/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val) {
    if (head == NULL) return NULL;

    struct ListNode* dummy = malloc(sizeof(struct ListNode));
    dummy->next = head;

    struct ListNode* prev = dummy;
    struct ListNode* curr = head;
    while (curr != NULL) {
        if (curr->val == val) {
            prev->next = curr->next;
            curr->next = NULL;
            curr = prev->next;
        } else {
            prev = curr;
            curr = curr->next;
        }
    }

    head = dummy->next;
    free(dummy);

    return head;
}